package fr.umlv.cmis.gedconfig;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;

import kiyut.ekspos.prefs.GeneralPreferences;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException;
import org.flexdock.docking.state.PersistenceException;
import org.flexdock.perspective.persist.PersistenceHandler;
import org.flexdock.perspective.persist.Persister;
import org.flexdock.perspective.persist.PerspectiveModel;
import org.flexdock.perspective.persist.xml.XMLPersister;

import fr.umlv.authentication.SessionHandler;
import fr.umlv.model.ClientModel;
import fr.umlv.utils.ExceptionUtils;

// TODO: Auto-generated Javadoc
/**
 * The Class GEDDockingPersistence.
 */
public  class GEDDockingPersistence implements PersistenceHandler {
	
	/** The Constant prefFile. */
	private final static File prefFile = new File(System.getProperty("user.home")+File.separatorChar+"gedPerspectivePrefs.xml");
	
	/** The session. */
	private final Session session = SessionHandler.getClientSession().getSession();
	
	/** The user name. */
	private final String userName = SessionHandler.getClientSession().getSessionParameters().get(SessionParameter.USER);
	
	/** The Constant CMIS_USER_HOME. */
	private final static String CMIS_USER_HOME = "/Espaces Utilisateurs/";
//	private final static String CMIS_USER_HOME = "/User Homes/";

	/* (non-Javadoc)
	 * @see org.flexdock.perspective.persist.PersistenceHandler#store(java.lang.String, org.flexdock.perspective.persist.PerspectiveModel)
	 */
	public boolean store(String persistenceKey, PerspectiveModel perspectiveModel) throws IOException, PersistenceException {
		boolean saved = false;
		/* Fichier de persistence en local */
		ByteArrayOutputStream byteos = new ByteArrayOutputStream(1024);

		/* Fichier à distance, si le dossier n'existe pas */
    	try {
    		session.getObjectByPath(CMIS_USER_HOME + userName + "/.gedconfig/");
		} catch (CmisObjectNotFoundException e) {
			ClientModel.createFolder(CMIS_USER_HOME + userName + "/", ".gedconfig");
		}
		
            boolean stored = createDefaultPersister().store(byteos, perspectiveModel);
            if (stored == true) {
                byte[] bytes = byteos.toByteArray();
                GeneralPreferences prefs = GeneralPreferences.getInstance();
                /* Sauvegarde locale */
                /* Sauvegarde à distance */
                try {
                	CmisObject objToUpdate = session.getObjectByPath(CMIS_USER_HOME + userName + "/.gedconfig/gedPerspectivePrefs.xml");
                	ClientModel.updateStreamCmisObject(objToUpdate, ByteBuffer.wrap(bytes));
        		} catch (CmisObjectNotFoundException e) {
        			ClientModel.createStreamCmisObject(CMIS_USER_HOME + userName + "/.gedconfig/", "gedPerspectivePrefs.xml", "text/xml",
        							ByteBuffer.wrap(bytes));
        		}
                prefs.putByteArray(GeneralPreferences.DOCKING_LAYOUT_KEY, bytes);
                prefs.save();
                saved = true;
            }
        return saved;
    }
    
    /* (non-Javadoc)
     * @see org.flexdock.perspective.persist.PersistenceHandler#load(java.lang.String)
     */
    public PerspectiveModel load(String persistenceKey) throws IOException, PersistenceException {
    	PerspectiveModel perspectiveModel = null;
    	GeneralPreferences prefs = GeneralPreferences.getInstance();
    	
    	try {
    		ClientModel.downloadCmisObject(session.getObjectByPath(CMIS_USER_HOME + userName + "/.gedconfig/gedPerspectivePrefs.xml"), prefFile);
    		if (!prefFile.exists())
    			try {
    				prefFile.createNewFile();
    			} catch (IOException e) {
    				ExceptionUtils.createJXErrorIOException(e, null);
    			}
    		FileInputStream is = new FileInputStream(prefFile);
    		String isStr = is.toString();
    		if (isStr.length()==0) {
    			is.close();
    			throw new IOException("Unable to open the docking preferences or is incorrect.");
    		}
    		byte[] buf = isStr.getBytes();
    		if (buf != null) {
    			try {
    				perspectiveModel = createDefaultPersister().load(is);
    			} finally {
    				if (is != null) {
    					is.close();
    				}
    			}
    		}
    		ClientModel.perspective_restored_ok = true;
    	} catch(FileNotFoundException fnfe) {
    		/* Mettre la disposition défaut */
    		byte[] bytes = prefs.getByteArray(GeneralPreferences.DOCKING_LAYOUT_KEY);
    		if (bytes != null) {
                java.io.ByteArrayInputStream is = new java.io.ByteArrayInputStream(bytes);
                try {
                    perspectiveModel = createDefaultPersister().load(is);
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
    	} catch (CmisObjectNotFoundException confe) {
    		/* Mettre la disposition défaut */
    		byte[] bytes = prefs.getByteArray(GeneralPreferences.DOCKING_LAYOUT_KEY);
    		if (bytes != null) {
                java.io.ByteArrayInputStream is = new java.io.ByteArrayInputStream(bytes);
                try {
                    perspectiveModel = createDefaultPersister().load(is);
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
    	}
        return perspectiveModel;
    }
    
    /* (non-Javadoc)
     * @see org.flexdock.perspective.persist.PersistenceHandler#createDefaultPersister()
     */
    public Persister createDefaultPersister() {
        return XMLPersister.newDefaultInstance();
    }

}